<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册 - 哔哩哔哩弹幕网</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script type="importmap">
    {
      "imports": {
        "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
      }
    }
    </script>
    <style>
        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .register-container {
            background: white;
            border-radius: 10px;
            padding: 2rem;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
            margin: 2rem auto;
            max-width: 500px;
        }
        .form-floating {
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container">
                <a class="navbar-brand" href="/">
                    <i class="fas fa-play-circle"></i> 哔哩哔哩弹幕网
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav me-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="/"><i class="fas fa-home"></i> 首页</a>
                        </li>
                    </ul>
                    <ul class="navbar-nav">
                        <li class="nav-item">
                            <a class="nav-link" href="/login.html">
                                <i class="fas fa-sign-in-alt"></i> 登录
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>

        <div class="container flex-grow-1">
            <div class="register-container">
                <h2 class="text-center mb-4">Create Account</h2>
                <form @submit="handleRegister" novalidate>
                    <div class="form-floating mb-3">
                        <input type="text" 
                               class="form-control" 
                               :class="{ 'is-invalid': errors.username }"
                               id="username" 
                               v-model="formData.username"
                               placeholder="Username" 
                               required
                               minlength="3" 
                               maxlength="20" 
                               pattern="[a-zA-Z0-9_]+">
                        <label for="username">Username</label>
                        <div class="invalid-feedback" v-if="errors.username">
                            {{ errors.username }}
                        </div>
                        <div class="invalid-feedback" v-else>
                            Username must be 3-20 characters long and contain only letters, numbers, and underscores.
                        </div>
                    </div>

                    <div class="form-floating mb-3">
                        <input type="email" 
                               class="form-control" 
                               :class="{ 'is-invalid': errors.email }"
                               id="email" 
                               v-model="formData.email"
                               placeholder="name@example.com" 
                               required>
                        <label for="email">Email address</label>
                        <div class="invalid-feedback" v-if="errors.email">
                            {{ errors.email }}
                        </div>
                        <div class="invalid-feedback" v-else>
                            Please enter a valid email address.
                        </div>
                    </div>

                    <div class="form-floating mb-3">
                        <input type="password" 
                               class="form-control" 
                               :class="{ 'is-invalid': errors.password }"
                               id="password" 
                               v-model="formData.password"
                               @input="validatePasswordMatch"
                               placeholder="Password" 
                               required
                               minlength="6" 
                               maxlength="50">
                        <label for="password">Password</label>
                        <div class="invalid-feedback" v-if="errors.password">
                            {{ errors.password }}
                        </div>
                        <div class="invalid-feedback" v-else>
                            Password must be at least 6 characters long.
                        </div>
                    </div>

                    <div class="form-floating mb-3">
                        <input type="password" 
                               class="form-control" 
                               :class="{ 'is-invalid': errors.confirmPassword }"
                               id="confirmPassword" 
                               v-model="formData.confirmPassword"
                               @input="validatePasswordMatch"
                               placeholder="Confirm Password" 
                               required>
                        <label for="confirmPassword">Confirm Password</label>
                        <div class="invalid-feedback" v-if="errors.confirmPassword">
                            {{ errors.confirmPassword }}
                        </div>
                        <div class="invalid-feedback" v-else>
                            Passwords do not match.
                        </div>
                    </div>

                    <div v-if="generalError" class="alert alert-danger">
                        {{ generalError }}
                    </div>

                    <button type="submit" 
                            class="btn btn-primary w-100 mb-3" 
                            :disabled="loading">
                        <i v-if="loading" class="fas fa-spinner fa-spin"></i>
                        <i v-else class="fas fa-user-plus"></i>
                        {{ loading ? '注册中...' : '注册' }}
                    </button>

                    <div class="text-center">
                        已有账号？<a href="/login.html" class="text-decoration-none">立即登录</a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script type="module">
        import { createApp, ref, reactive, watch, onMounted } from 'vue';
        import { authState, showToast } from '/js/auth.js';

        createApp({
            setup() {
                const formData = ref({
                    username: '',
                    email: '',
                    password: '',
                    confirmPassword: ''
                });
                
                const loading = ref(false);
                const generalError = ref('');
                const errors = reactive({
                    username: '',
                    email: '',
                    password: '',
                    confirmPassword: ''
                });

                const validatePasswordMatch = () => {
                    if (formData.value.password && formData.value.confirmPassword) {
                        if (formData.value.password !== formData.value.confirmPassword) {
                            errors.confirmPassword = 'Passwords do not match';
                        } else {
                            errors.confirmPassword = '';
                        }
                    }
                };

                const validateForm = () => {
                    // Reset errors
                    Object.keys(errors).forEach(key => errors[key] = '');
                    
                    let isValid = true;

                    // Username validation
                    if (!formData.value.username) {
                        errors.username = 'Username is required';
                        isValid = false;
                    } else if (formData.value.username.length < 3 || formData.value.username.length > 20) {
                        errors.username = 'Username must be 3-20 characters long';
                        isValid = false;
                    } else if (!/^[a-zA-Z0-9_]+$/.test(formData.value.username)) {
                        errors.username = 'Username can only contain letters, numbers, and underscores';
                        isValid = false;
                    }

                    // Email validation
                    if (!formData.value.email) {
                        errors.email = 'Email is required';
                        isValid = false;
                    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.value.email)) {
                        errors.email = 'Please enter a valid email address';
                        isValid = false;
                    }

                    // Password validation
                    if (!formData.value.password) {
                        errors.password = 'Password is required';
                        isValid = false;
                    } else if (formData.value.password.length < 6) {
                        errors.password = 'Password must be at least 6 characters long';
                        isValid = false;
                    }

                    // Confirm password validation
                    if (!formData.value.confirmPassword) {
                        errors.confirmPassword = 'Please confirm your password';
                        isValid = false;
                    } else if (formData.value.password !== formData.value.confirmPassword) {
                        errors.confirmPassword = 'Passwords do not match';
                        isValid = false;
                    }

                    return isValid;
                };

                const handleRegister = async (event) => {
                    event.preventDefault();
                    
                    // Reset errors
                    generalError.value = '';
                    
                    if (!validateForm()) {
                        return;
                    }

                    loading.value = true;

                    try {
                        // Send registration request
                        const response = await axios.post('/api/auth/register', {
                            username: formData.value.username,
                            email: formData.value.email,
                            password: formData.value.password
                        });

                        console.log('Registration response:', response.data);

                        // Check if registration was successful (session-based, not token-based)
                        if (response.data && response.data.user) {
                            // Show success message
                            showToast('注册成功! 正在跳转...', 'success');
                            
                            // Update global auth state
                            authState.currentUser = response.data.user;
                            authState.isAuthenticated = true;
                            
                            // Redirect to home page after a short delay
                            setTimeout(() => {
                                window.location.href = '/';
                            }, 1500);
                        } else {
                            generalError.value = '注册失败，请重试';
                        }
                    } catch (error) {
                        console.error('Registration error:', error);
                        const errorMessage = error.response?.data?.error || '注册失败，请重试';
                        generalError.value = errorMessage;
                    } finally {
                        loading.value = false;
                    }
                };

                return {
                    formData,
                    loading,
                    generalError,
                    errors,
                    validatePasswordMatch,
                    handleRegister
                };
            }
        }).mount('#app');
    </script>
</body>
</html>
